package com.miao.hong.fang.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ConfigProperties {

	private static ConfigProperties instance;
	private static Properties[] properties = new Properties[2];
	private static String[] propertiesNames = new String[2];
	
	public static ConfigProperties getInstance() {
		if(instance != null) {
			return instance;
		}
		return new ConfigProperties();
	}
	
	private Properties loadProperties(String propertyFileName) {
		InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertyFileName + ".properties");		
		Properties result = null;
		if (is != null) {
			try {
				for(int i = 0; i < properties.length; i++) {
					if(properties[i] == null) {
						propertiesNames[i] = propertyFileName;
						properties[i] = new Properties();
						properties[i].load(is);
						result = properties[i]; 
						is.close();						
						break;
					}
				}   				
			}catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					is.close();
					is = null;
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
        }
		return result;
	}
	
	public String getProperties(String propertyFileName, String propertyName, String defaultValue) {
		
		boolean loaded = false;
		String result = "";
		for(int i = 0; i < propertiesNames.length; i++) {
			if(propertyFileName.equals(propertiesNames[i])) {
				loaded = true;
				result = properties[i].getProperty(propertyName, defaultValue);
				break;
			}
		}
		if(!loaded) {
			Properties properties = loadProperties(propertyFileName);
			if(properties != null) {
				result = properties.getProperty(propertyName, defaultValue);
			}
		}
		return result;
	}
}
